package cn.edu.gcu.ssl.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.gcu.ssl.system.service.impl.ISendMessage;
import cn.edu.gcu.ssl.system.util.HttpUtils;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value="")
public class SendMessageController {


//	@Resource(name="sendMessagSerice")
//	private ISendMessage messageService;

	@Value("${task.weiboPath}")
	private String weiboPath; // 讯通地址
	
	@Value("${task.basePath}")
	private String basePath; // 应用的ip和端口
	
	@Value("${eid}")
	private String eid; // 工作圈id
	
	@Value("${appid}")
	private String appid; // 应用id
	
	@Value("${appsecret}")
	private String appsecret; // 应用秘钥
	
	@Value("${task.pubId}")
	private String pubId; // 公共号id
	
	@Value("${task.pubKey}")
	private String pubKey; // 公共号秘钥
	
	
	
	@ResponseBody	
	@RequestMapping(value="/access")
	public ModelAndView demo(@RequestParam(value="ticket",required=false)String ticket,HttpServletRequest request,HttpServletResponse response)
	{
		ModelAndView mv = new ModelAndView("/error"); //需要更改为错误页面
		if(ticket==null)
		{
			return mv;
		}

		request.getSession().setAttribute("ticket", ticket);
	try {
		//获取token
		String url_token=weiboPath+"/openauth2/api/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
		String string_access_token=HttpUtils.post(url_token, "", "");
		JSONObject json_access_token=JSONObject.fromObject(string_access_token);
		String access_token=json_access_token.get("access_token").toString();
		//获取上下文
		String url = weiboPath+"/openauth2/api/getcontext?ticket="+ticket+"&access_token="+access_token;	
		String string_persionInfo=HttpUtils.post(url, "", "");
		if(string_persionInfo!=null)
		{
			JSONObject json_persionInfo=JSONObject.fromObject(string_persionInfo);
			if(json_persionInfo!=null)
			{
				String openid=json_persionInfo.get("openid").toString();
				String username=json_persionInfo.get("username").toString();
				request.getSession().setAttribute("openid", openid);
				request.getSession().setAttribute("username",username);
				mv.addObject("openid",openid);//用户id
				mv.setViewName("/index");   //需要更改为主页面
				return mv;
			}
		}
		}catch(Exception e){
			e.printStackTrace();
		}
	
		return mv;
		
		
	}
	
	
		
	
	
	
	
	
	
	
	
	
	
	
	
	
}
	
	
	
	
	

